import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:second_hand/pages/forget_password.dart';
import '../API/user/user.dart';
import '../data/profile_data.dart';
import '../data/shared_preferences_service.dart';
import 'home/NavigatorHomePage.dart';

class LoginController extends GetxController {
  final GlobalKey<FormFieldState> passwordKey = GlobalKey();
  RxBool showPassword = false.obs;
  RxBool isChecked = false.obs;
  RxString phone = ''.obs;
  RxString password = ''.obs;
  final TextEditingController passwordController = TextEditingController();

  @override
  void onClose() {
    passwordController.dispose();
    super.onClose();
  }

  void clear() {
    showPassword.value = false;
    isChecked.value = false;
    phone.value = '';
    password.value = '';
  }

  bool validateForm() {
    if (phone.value.isEmpty) {
      Get.snackbar("提示", "请输入账号", snackPosition: SnackPosition.TOP);
      return false;
    }
    if (password.value.length < 6) {
      Get.snackbar("提示", "密码最少六个字符", snackPosition: SnackPosition.TOP);
      return false;
    }
    return true;
  }

  Future<void> login() async {
    if (validateForm()) {
      final response = await ApiService.login(phone.value, password.value);
      final int code = response["code"];

      if (code == 10021) {
        await SharedPreferencesService.saveToken(response["data"]);
        Get.find<UserController>().getUserInfo();
        Get.offAll(const NavigatorHomePage());
        Get.snackbar("登陆成功", "", snackPosition: SnackPosition.TOP);
        clear();
      } else {
        Get.snackbar(
          code == 10020 ? "账号或密码错误" : "未知错误",
          code != 10020 ? "登陆失败: ${response['message']}" : "",
          snackPosition: SnackPosition.TOP,
          duration: Duration(seconds: code == 10020 ? 2 : 5),
        );
      }
    }
  }
}

class LoginPage extends StatelessWidget {
  LoginPage({super.key});
  final LoginController controller = Get.put(LoginController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        backgroundColor: const Color(0xFF0088FF),
        foregroundColor: Colors.white,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: Get.back,
        ),
      ),
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFF0088FF), Colors.cyanAccent],
          ),
        ),
        child: ListView(
          children: [
            const SizedBox(height: 40),
            _buildWelcomeText(),
            _buildLoginForm(),
            _buildBottomLinks(),
            _buildAgreement(),
          ],
        ),
      ),
    );
  }

  Widget _buildWelcomeText() {
    return const Padding(
      padding: EdgeInsets.all(40),
      child: Text(
        'Welcome',
        style: TextStyle(
          color: Colors.white,
          fontSize: 32,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  Widget _buildLoginForm() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(40, 0, 40, 0),
      child: Column(
        children: [
          _buildPhoneField(),
          const SizedBox(height: 20),
          _buildPasswordField(),
          const SizedBox(height: 40),
          _buildLoginButton(),
          const SizedBox(height: 20),
        ],
      ),
    );
  }

  Widget _buildPhoneField() {
    return  TextFormField(
      decoration: const InputDecoration(
        labelText: '账号',
        hintText: '学号/手机号/邮箱(目前只能手机号)',
        labelStyle: TextStyle(color: Colors.white),
        hintStyle: TextStyle(color: Colors.white),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.blue),
        ),
      ),
      keyboardType: TextInputType.phone,
      style: const TextStyle(color: Colors.white),
      controller: TextEditingController(text: controller.phone.value),
      onChanged: (value) => controller.phone.value = value,
    );
  }

  Widget _buildPasswordField() {
    return Obx(()=>
        TextFormField(
          key: controller.passwordKey,
          decoration: InputDecoration(
            labelText: '密码',
            hintText: '请输入密码',
            labelStyle: const TextStyle(color: Colors.white),
            hintStyle: const TextStyle(color: Colors.white),
            suffixIcon: IconButton(
              icon:
              Icon(
                controller.showPassword.value
                    ? Icons.visibility_off
                    : Icons.visibility,
                color: Colors.white,
              ),

              onPressed: controller.showPassword.toggle,
            ),
            enabledBorder: const UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.white),
            ),
            focusedBorder: const UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.blue),
            ),
          ),
          style: const TextStyle(color: Colors.white),
          obscureText: !controller.showPassword.value,
          controller: controller.passwordController,
          onChanged: (value) => controller.password.value = value,
        ),
    );
  }

  Widget _buildLoginButton() {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        backgroundColor: Colors.white,
        foregroundColor: Colors.blue,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20),
        ),
        padding: const EdgeInsets.symmetric(horizontal: 80),
      ),
      onPressed: controller.login,
      child: const Text('登录'),
    );
  }

  Widget _buildBottomLinks() {
    return Padding(
      padding: const EdgeInsets.only(right: 30),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          TextButton(
            onPressed: () {/* todo */},
            child: const Text('短信登录(todo)', style: TextStyle(color: Colors.white)),
          ),
          const SizedBox(width: 20),
          TextButton(
            onPressed: () {
            Get.to(()=>ForgetPasswordPage());
            },
            child: const Text('忘记密码？', style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
    );
  }

  Widget _buildAgreement() {
    return Padding(
      padding: const EdgeInsets.all(15),
      child:  Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          GestureDetector(
            onTap: controller.isChecked.toggle,
            child: Obx(()=>
                Icon(
                  controller.isChecked.value
                      ? Icons.check_box_outlined
                      : Icons.check_box_outline_blank,
                  color: Colors.white,
                  size: 20,
                ),
            ),
          ),
          const SizedBox(width: 10),
          const Text('我已阅读并同意 ',
              style: TextStyle(color: Colors.white, fontSize: 14)),
          GestureDetector(
            onTap: () {/* todo */},
            child: const Text('《用户协议》',
                style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.bold)),
          ),
          const Text(' 与 ',
              style: TextStyle(color: Colors.white, fontSize: 14)),
          GestureDetector(
            onTap: () {/* todo */},
            child: const Text('《隐私政策》',
                style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.bold)),
          ),
        ],
      ),
    );
  }
}